<template>
  <div class="list-container">
    <!-- 搜索栏 -->
    <div class="list-header">
      <div class="search-form">
        <div class="search-form-item">
          <label>退款单号(ID)</label>
          <el-input v-model="searchForm.refundNumber" placeholder="请输入退款单号" clearable @keyup.enter="handleSearch" />
        </div>
        <div class="search-form-item">
          <label>用户ID</label>
          <el-input v-model="searchForm.userId" placeholder="请输入用户ID" clearable @keyup.enter="handleSearch" />
        </div>
        <div class="search-form-item">
          <label>订单ID</label>
          <el-input v-model="searchForm.orderId" placeholder="请输入订单ID" clearable @keyup.enter="handleSearch" />
        </div>
        <div class="search-form-item">
          <label>处理状态</label>
          <el-select v-model="searchForm.processStatus" placeholder="全部" clearable @change="handleSearch">
            <el-option label="处理中" value="处理中" />
            <el-option label="已退款" value="已退款" />
            <el-option label="已拒绝" value="已拒绝" />
          </el-select>
        </div>
      </div>
      <div class="search-actions">
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="success" @click="handleAdd">新增退款</el-button>
        <el-button type="danger" :disabled="!multipleSelection.length" @click="handleBatchDelete">
          批量删除
        </el-button>
      </div>
    </div>

    <!-- 表格内容 -->
    <div class="list-content">
      <div class="list-table">
        <el-table
          ref="multipleTableRef"
          :data="tableData"
          style="width: 100%; height: 100%"
          border
          v-loading="loading"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column prop="id" label="退款单号" width="100" align="center" />
          <el-table-column prop="userId" label="用户ID" width="100" align="center" />
          <el-table-column prop="orderId" label="订单ID" width="100" align="center" />
          <el-table-column prop="refundAmount" label="退款金额" width="120" align="center">
            <template #default="scope">
              ¥{{ scope.row.refundAmount }}
            </template>
          </el-table-column>
          <el-table-column prop="refundReason" label="退款原因" min-width="150" show-overflow-tooltip />
          <el-table-column prop="applyTime" label="申请时间" width="160" align="center">
            <template #default="scope">
              {{ formatDate(scope.row.applyTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="processStatus" label="处理状态" width="100" align="center">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.processStatus)">
                {{ scope.row.processStatus }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="refundTime" label="退款时间" width="160" align="center">
            <template #default="scope">
              {{ formatDate(scope.row.refundTime) }}
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="150" align="center" fixed="right">
            <template #default="scope">
              <div class="action-buttons">
                <el-button link type="primary" @click="handleEdit(scope.row)">处理</el-button>
                <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 分页 -->
    <div class="list-footer">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 弹窗 -->
    <RefundDialog
      v-model:visible="dialogVisible"
      :is-edit="isEdit"
      :form-data="currentRefund"
      :loading="dialogLoading"
      @submit="handleDialogSubmit"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getRefundList, deleteRefund, batchDeleteRefunds, updateRefund, createRefund } from '@/api/refund'
import RefundDialog from '@/components/dialogs/RefundDialog.vue'

// 搜索表单
const searchForm = reactive({
  refundNumber: '',
  userId: '',
  orderId: '',
  processStatus: ''
})

const tableData = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const multipleSelection = ref([])

// 弹窗相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const currentRefund = ref(null)
const dialogLoading = ref(false)

onMounted(() => {
  fetchData()
})

const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      refundNumber: searchForm.refundNumber || undefined,
      userId: searchForm.userId || undefined,
      orderId: searchForm.orderId || undefined,
      processStatus: searchForm.processStatus || undefined
    }
    const res = await getRefundList(params)
    if (res.success) {
      tableData.value = res.data.data
      total.value = res.data.total
    } else {
      ElMessage.error(res.msg || '获取数据失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

const resetSearch = () => {
  searchForm.refundNumber = ''
  searchForm.userId = ''
  searchForm.orderId = ''
  searchForm.processStatus = ''
  handleSearch()
}

const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

const handleAdd = () => {
  isEdit.value = false
  currentRefund.value = null
  dialogVisible.value = true
}

const handleEdit = (row) => {
  isEdit.value = true
  currentRefund.value = { ...row }
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该退款记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteRefund(row.id)
      if (res.success) {
        ElMessage.success('删除成功')
        fetchData()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

const handleBatchDelete = () => {
  if (!multipleSelection.value.length) return
  ElMessageBox.confirm(`确认删除选中的 ${multipleSelection.value.length} 条记录吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const ids = multipleSelection.value.map(item => item.id)
      const res = await batchDeleteRefunds(ids)
      if (res.success) {
        ElMessage.success('批量删除成功')
        fetchData()
      } else {
        ElMessage.error(res.msg || '批量删除失败')
      }
    } catch (error) {
      ElMessage.error('批量删除失败')
    }
  })
}

const handleDialogSubmit = async (formData) => {
  dialogLoading.value = true
  try {
    let res
    if (isEdit.value) {
      res = await updateRefund(currentRefund.value.id, formData)
    } else {
      res = await createRefund(formData)
    }
    
    if (res.success) {
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      dialogVisible.value = false
      fetchData()
    } else {
      ElMessage.error(res.msg || (isEdit.value ? '更新失败' : '创建失败'))
    }
  } catch (error) {
    console.error(error)
    ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
  } finally {
    dialogLoading.value = false
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  return dateStr.replace('T', ' ').replace(/\.\d+\+\d+:\d+$/, '')
}

const getStatusType = (status) => {
  switch (status) {
    case '已退款': return 'success'
    case '已拒绝': return 'danger'
    case '处理中': return 'warning'
    default: return 'info'
  }
}
</script>

<style scoped>
@import "@/assets/css/table-list.css";
</style>
